import {Divider, Popconfirm, Table, DatePicker, Select } from 'antd'
import React, { useState, useEffect } from 'react'
import styles from "@/pages/Info/Edit/style.less";
import { connect } from 'umi'
import moment from 'moment'
import {jobLevelTypeList, probationDayList } from '@/utils/constant'
import { getPromotion,getJobByOrgId} from '../../service'
import { findItemByTree } from '@/utils/functions'

const { Option } = Select

const TableForm = ({userList,tempUnitTree,onChange,jobLevel}) => {
  const [clickedCancel, setClickedCancel] = useState(false);
  const [loading, setLoading] = useState(false);
  const [cacheOriginData, setCacheOriginData] = useState({});
  const [data, setData] = useState([]);
  const [jobList,setJobList] = useState([]);
  const [jobTemp,setJobTemp] = useState([]);
  const [tempJobLevel,setTempJobLevel] = useState([]);

  useEffect(() => {
    onChangeJobLevelType(2);
    setLoading(true);
    if(userList.length < 1){
      setData([])
    }else {
      let newTempData = [];
      userList.forEach((item,index) => {
        newTempData.push({...item, key:item.code, promotionType:2, promotionDate: item.beginExpeditionDate || new Date() })
      });
      setData(newTempData);
    }
    setLoading(false);
  }, [userList]);

  const getRowByKey = (key, newData) => (newData || data)?.filter((item) => item.key === key)[0]

  const toggleEditable = (e, key, type) => {
    e.preventDefault();
    const newData = data?.map((item) => ({ ...item }));
    const target = getRowByKey(key, newData);
    if (target) {
      // 进入编辑状态时保存原始数据
      if (!target.editable) {
        cacheOriginData[key] = { ...target };
        setCacheOriginData(cacheOriginData);
        getDeptJobList(target.unitId);
      }
      target.editable = !target.editable;
      if (type === 'save'){
        onChange(newData)
      }else {
        setData(newData);
      }
    }
  };

  const onChangeJobLevelType = (e) => {
    if (e === 2) {
      setTempJobLevel(jobLevel.filter(e => e.type === 'CODE_MANAGEMENTRANK').reverse())
    } else {
      setTempJobLevel(jobLevel.filter(e => e.type === 'CODE_PROFESSIONALRANK').reverse())
    }
  }

  const remove = (e, key) => {
    const newData = [...data];
    let dataList = newData.filter(item => item.key !== key);
    onChange(dataList,true);
  };

  const handleFieldChange = (e, fieldName, key) => {
    const newData = [...data];
    const target = getRowByKey(key, newData);
    if (target) {
      target[fieldName] = e.target ? e.target.value : e;
      setData(newData);
    }
  };

  const computeDay = (e, fieldName, key) =>{
    const newData = [...data];
    const target = getRowByKey(key, newData)
    if (target) {
      target[fieldName] = e.target ? e.target.value : e;
      let ctm = moment(target.beginExpeditionDate);
      let etm = ctm.add(target.expeditionDays,'M');
      target.endExpeditionDate = etm;
      setData(newData)
    }
  };

  const getDeptJobList = (id) => {
    let temp = jobTemp
    getJobByOrgId(id).then((res) => {
      setJobList(res?res:[])
      setJobTemp(temp.concat(res))
    })
  }

  const updateRow = (e, rowKey) => {
    e.persist();
    if (clickedCancel) {
      setClickedCancel(false);
      return
    }
    toggleEditable(e, rowKey, 'save');
  };

  const cancel = (e, key) => {
    setClickedCancel(true);
    e.preventDefault();
    const newData = [...data];
    let cacheData = newData.map((item) => {
      if (item.key === key) {
        // 编辑前的原始数据
        if (cacheOriginData[key]) {
          const originItem = { ...cacheOriginData[key], editable: false };
          delete cacheOriginData[key];
          setCacheOriginData(cacheOriginData);
          return originItem
        }
      }
      return item
    });
    onChange(cacheData);
    setClickedCancel(false)
  };

  const columns = [
    {
      title: '工号',
      dataIndex: 'code',
      key: 'code',
      disabled:true,
      width: 110,
      fixed: 'left'
    },
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
      disabled:true,
      width: 100,
      fixed: 'left'
    },
    {
      title: '部门',
      dataIndex: 'unitId',
      disabled:true,
      width: 150,
      render:(text) => {
        return  findItemByTree(tempUnitTree,parseInt(text))?.title;
      }
    },
    {
      title: '晋升日期',
      dataIndex: 'promotionDate',
      key: 'promotionDate',
      width: 150,
      render: (text, record) => {
        // if (record.editable) {
        //   return (
        //     <DatePicker placeholder="请选择日期" value={moment(text)}
        //                 onChange={(e) => handleFieldChange(e, 'promotionDate', record.key)}/>
        //   )
        // }
        return moment(record.beginExpeditionDate).format('YYYY-MM-DD')
      },
    },
    {
      title: '晋级类型',
      dataIndex: 'promotionType',
      key: 'promotionType',
      width: 150,
      render: (text, record) => {
        // if (record.editable) {
        //   return (
        //     <Select placeholder="请选择" value={text} onChange={(e) => handleFieldChange(e, 'promotionType', record.key)}>
        //       {jobLevelTypeList.map((item, index) => {
        //         return (
        //           <Option value={item.value} key={index}>
        //             {item.label}
        //           </Option>
        //         )
        //       })}
        //     </Select>
        //   )
        // }
        const res = jobLevelTypeList.find((item) => item.value === parseInt(text))
        return res ? res.label : text
      },
    },
    {
      title: '晋升后部门',
      dataIndex: 'unitId',
      width: 200,
      render:(text) => {
        return  findItemByTree(tempUnitTree,parseInt(text))?.title;
      }
    },
    {
      title: '晋升后岗位',
      dataIndex: 'afterJobId',
      key: 'afterJobId',
      width: 200,
      render: (text, record) => {
        if (record.editable) {
          return (
            <Select placeholder="请选择" value={text} onChange={(e) => handleFieldChange(e, 'afterJobId', record.key)}>
              {jobList.map((item, index) => {
                return (
                  <Option value={`${item.coidassignedjob}`} key={item.coidassignedjob}>
                    {item.cname}
                  </Option>
                )
              })}
            </Select>
          )
        }
        const res = jobTemp.find((item) => item.coidassignedjob === text)
        return res ? res.cname : text
      },
    },
    {
      title: '晋升后职级',
      dataIndex: 'afterJobLevelId',
      key: 'afterJobLevelId',
      width: 150,
      render: (text, record) => {
        if (record.editable) {
          return (
            <Select placeholder="请选择" value={text} onChange={(e) => handleFieldChange(e, 'afterJobLevelId', record.key)}>
              {tempJobLevel?.map((item, index) => {
                return (
                  <Option value={`${item.id}`} key={item.id}>
                    {item.name}
                  </Option>
                )
              })}
            </Select>
          )
        }
        const res = jobLevel.find((item) => item.id === text)
        return res ? res.name : text
      },
    },
    {
      title: '考察期开始日期',
      dataIndex: 'beginExpeditionDate',
      key: 'beginExpeditionDate',
      width: 150,
      render: (text, record) => {
        if (record.editable) {
          return (
            <DatePicker placeholder="请选择日期" style={{ width: '100%' }} value={text && moment(text)}
                        onChange={(e) => handleFieldChange(e, 'beginExpeditionDate', record.key)}/>
          )
        }
        return text && moment(text).format('YYYY-MM-DD')
      },
    },
    {
      title: '考察期',
      dataIndex: 'expeditionDays',
      width: 150,
      render: (text, record) => {
        if (record.editable) {
          return (
            <Select placeholder="请选择" onChange={(e) => computeDay(e, 'expeditionDays', record.key)}>
              {probationDayList.map((item, index) => {
                return (
                  <Option value={item.value} key={item.value}>
                    {item.label}
                  </Option>
                )
              })}
            </Select>
          )
        }
        return probationDayList.find(e => text === e.value)?.label;
      },
    },
    {
      title: '考察期结束日期',
      dataIndex: 'endExpeditionDate',
      width: 150,
      render: (text) => {
        return text && moment(text).format('YYYY-MM-DD');
      },
    },
    {
      title: '操作',
      key: 'action',
      width: 110,
      fixed: 'right',
      render: (text, record) => {
        if (!!record.editable && loading) {
          return null
        }

        if (record.editable) {
          return (
            <span>
              <a onClick={(e) => updateRow(e, record.key, record.oid)}>保存</a>
              <Divider type="vertical"/>
              <a onClick={(e) => cancel(e, record.key)}>取消</a>
            </span>
          )
        }

        return (
          <span>
            <a onClick={(e) => toggleEditable(e, record.key)}>编辑</a>
            <Divider type="vertical"/>
            <Popconfirm title="是否要删除此行？" cancelText='取消' okText='确认' onConfirm={(e) => remove(e, record.key)}>
              <a>删除</a>
            </Popconfirm>
          </span>
        )
      },
    },
  ]
  return (
    <>
      <Table
        loading={loading}
        columns={columns}
        dataSource={data}
        pagination={false}
        rowClassName={(record) => (record.editable ? styles.editable : '')}
        scroll={{x:1000}}
      />
    </>
  )
}

export default connect(({ recruitment }) => ({
  recruitment,
}))(TableForm)

